package com.xinghai.admin.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.json.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xinghai.admin.domain.SysNoticeRead;
import com.xinghai.admin.mapper.SysNoticeReadMapper;
import com.xinghai.admin.mapper.SysUserMapper;
import com.xinghai.admin.service.ISysNoticeReadService;
import com.xinghai.common.core.domain.entity.SysUser;
import com.xinghai.common.core.domain.model.LoginUser;
import com.xinghai.common.utils.HtmlFormatUtil;
import com.xinghai.common.utils.SecurityUtils;
import com.xinghai.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xinghai.admin.domain.SysNotice;
import com.xinghai.admin.mapper.SysNoticeMapper;
import com.xinghai.admin.service.ISysNoticeService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 公告 服务层实现
 *
 * @author xinghai
 */
@Service
public class SysNoticeServiceImpl implements ISysNoticeService
{
    @Autowired
    private SysNoticeMapper noticeMapper;
    @Autowired
    private ISysNoticeReadService sysNoticeReadService;

    @Autowired
    private SysUserMapper userMapper;

    /**
     * 查询公告信息
     *
     * @param noticeId 公告ID
     * @return 公告信息
     */
    @Override
    public SysNotice selectNoticeById(Long noticeId)
    {
        return selectNoticeById(noticeId,false);
    }

    @Override
    public SysNotice selectNoticeById(Long noticeId,boolean isRead)
    {
        if (isRead){
            LoginUser loginUser = SecurityUtils.getLoginUser();
            SysNoticeRead notice = new SysNoticeRead();
            notice.setReadStatus("1");
            LambdaQueryWrapper<SysNoticeRead> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysNoticeRead::getNoticeId,noticeId)
                    .eq(SysNoticeRead::getUserId,loginUser.getUserId());
            sysNoticeReadService.update(notice,queryWrapper);
        }
        return noticeMapper.selectNoticeById(noticeId);
    }

    /**
     * 查询公告列表
     *
     * @param notice 公告信息
     * @return 公告集合
     */
    @Override
    public List<SysNotice> selectNoticeList(SysNotice notice)
    {
        return noticeMapper.selectNoticeList(notice);
    }

    /**
     * 新增公告
     *
     * @param notice 公告信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertNotice(SysNotice notice)
    {
        notice.setNoticeAbstracts(HtmlFormatUtil.formatLength(notice.getNoticeContent()));
        if ("2".equals(notice.getNoticeType())){
            List<SysNoticeRead> sysNoticeReads = new ArrayList<>();
            /**
             * 群发传递参数
             */
            Map<String, Object> params = new HashMap<>();
            params.put("type","1");
            String paramsData = JSONObject.toJSONString(params);

            if ("0".equals(notice.getSendType())){
                List<SysUser> sysUsers = userMapper.selectUserList(new SysUser());
                List<Long> userList = sysUsers.stream().map(SysUser::getUserId).collect(Collectors.toList());
                sysNoticeReads = insertNoticeRead(userList,paramsData,notice);
            }
            else if ("1".equals(notice.getSendType()) && StringUtils.isNotBlank(notice.getSendUser())){
                String[] split = notice.getSendUser().split(",");
                List<SysUser> sysUsers = new ArrayList<>();
                for (String str : split) {
                    SysUser sysUser = new SysUser();
                    sysUser.setDeptId(Long.valueOf(str));
                    List<SysUser> sysUsers1 = userMapper.selectUserList(sysUser);
                    if (!sysUsers1.isEmpty()){
                        sysUsers.addAll(sysUsers1);
                    }
                }
                Set<SysUser> sysUsersSet = new HashSet<>(sysUsers); // 将List转为Set
                List<SysUser> uniqueList = new ArrayList<>(sysUsersSet); // 将Set转为List
                List<Long> userList = uniqueList.stream().map(SysUser::getUserId).collect(Collectors.toList());
                sysNoticeReads = insertNoticeRead(userList,paramsData,notice);
            }
            else if ("2".equals(notice.getSendType()) && StringUtils.isNotBlank(notice.getSendUser())){
                String[] split = notice.getSendUser().split(",");
                List<Long> collect = Arrays.stream(split).map(Long::valueOf).collect(Collectors.toList());
                sysNoticeReads = insertNoticeRead(collect,paramsData,notice);
            }
            if (sysNoticeReads.isEmpty()){
                return noticeMapper.insertNotice(notice);
            }
            noticeMapper.insertNotice(notice);
            sysNoticeReads.forEach(read->read.setNoticeId(notice.getNoticeId()));
            return sysNoticeReadService.importData(sysNoticeReads) ? 1 : 0;
        }
        return noticeMapper.insertNotice(notice);
    }

    public List<SysNoticeRead> insertNoticeRead(List<Long> userIds,String paramsData,SysNotice notice)
    {
        List<SysNoticeRead> sysNoticeReads = new ArrayList<>();
        for (Long userId : userIds) {
            SysNoticeRead sysNoticeRead = new SysNoticeRead();
            sysNoticeRead.setUserId(userId);
            sysNoticeRead.setNoticeAbstracts(notice.getNoticeAbstracts());
            sysNoticeRead.setNoticeTitle(notice.getNoticeTitle());
            sysNoticeRead.setCreateTime(new Date());
            sysNoticeRead.setReadStatus("0");
            sysNoticeRead.setParamsData(paramsData);
            sysNoticeReads.add(sysNoticeRead);
        }
        return sysNoticeReads;
    }
    /**
     * 修改公告
     *
     * @param notice 公告信息
     * @return 结果
     */
    @Override
    public int updateNotice(SysNotice notice)
    {
        return noticeMapper.updateNotice(notice);
    }

    /**
     * 删除公告对象
     *
     * @param noticeId 公告ID
     * @return 结果
     */
    @Override
    public int deleteNoticeById(Long noticeId)
    {
        return noticeMapper.deleteNoticeById(noticeId);
    }

    /**
     * 批量删除公告信息
     *
     * @param noticeIds 需要删除的公告ID
     * @return 结果
     */
    @Override
    public int deleteNoticeByIds(Long[] noticeIds)
    {
        return noticeMapper.deleteNoticeByIds(noticeIds);
    }
}
